<?php

/**
 *
 * 版权所有：恰维网络<qwadmin.qiawei.com>
 * 作    者：寒川<hanchuan@qiawei.com>
 * 日    期：2016-01-20
 * 版    本：1.0.0
 * 功能说明：用户控制器。
 *
 * */

namespace Qwadmin\Controller;

use Common\Controller\OdooApiController;
use Common\Upload;

//use Common\Controller\openerp;

class GoodspoController extends ComController {

    function uplode() {
        if ($_POST) {
//            echo "<pre>";
//            var_dump($_POST);die;
            $poname = I("post.ponum", "");
            $fmap = I("post.fmap", "");
            $filePath = base64_decode(I("filepath", ""));
            if (!$poname) {
                @unlink($filePath);
                $this->error("批次为空");
            }
            $opModel = M('product_po');
            $opdata = $opModel->where(array('PO_name' => $poname))->find();
            if ($opdata) {
                @unlink($filePath);
                $this->error("批次号已存在  ");
            }
            if (!$filePath || !file_exists($filePath)) {
                @unlink($filePath);
                $this->error("上传的文件不存在  ");
            }
            $PHPExcel = getExcelObj($filePath);
            if (!$PHPExcel) {
                @unlink($filePath);
                $this->error("文件读取失败请重试  ");
            }

            set_time_limit(0);
            //处理字段映射
            //默认第一张表的数据
            $currentSheet = $PHPExcel->getSheet(0);
            //取得一共有多少列  
            $allColumn = $currentSheet->getHighestColumn();
            //取得一共有多少行  
            $allRow = $currentSheet->getHighestRow();
            //判断数据的条数
            if ($allRow <= 1) {
                exit('<script>parent.title = "上传的execl无数据，或者已损坏！";parent.code = "error";parent.tips_msg()</script>');
            }
            $fields = array();
            foreach ($fmap as $key => $value) {
                if (!$value[0] || !$value[1]) {
                    continue;
                }
                $fields[$value[1]] = array($value[0], $value[1]);
            }

//           var_dump($fields);die;
            $num = array(); //成功条数
            $error_num = array(); //错误条数
            $repeat_num = array(); //重复条数
            //循环读取数据,默认是utf-8输出
            $model = M('product_po');
            $goodsmodel = D('Goods');

            for ($currentRow = 1; $currentRow <= $allRow; $currentRow++) {
//                echo $currentRow."---- {$allRow}----   <br>";
                if ($currentRow <= 1)
                    continue;
                $add_data = array();

                $flag = false;
                foreach ($fields as $keey => $v) {
                    $add_data[$v[0]] = $PHPExcel->getActiveSheet()->getCell($keey . $currentRow)->getValue();
                    if ($add_data[$v[0]]) {
                        $flag = true;
                    }
                    if ($v[0] == "exp_time") {
                        $add_data["exp_time"] = date("Y-m-d", \PHPExcel_Shared_Date::ExcelToPHP($add_data["exp_time"]));
                    }
                }
				//var_dump($add_data);
				//die();
                if (!$flag) {
                    break;
                }
                if (isset($add_data['goods_brand_id']) && !empty($add_data['goods_brand_id'])) {
                    $add_data['goods_brand_id'] = $goodsmodel->getBrand_idBy_name($add_data['goods_brand_id']);
                }
                if (isset($add_data['made_in']) && !empty($add_data['made_in'])) {
                    $add_data['made_in'] = $goodsmodel->getMadein_IDBy_name($add_data['made_in']);
                }
                if (isset($add_data['info_keywords']) && !empty($add_data['info_keywords'])) {
                    $add_data['info_keywords'] = json_encode(explode("、",$add_data['info_keywords']));
                }
                if (isset($add_data['trade_type']) && !empty($add_data['trade_type'])) {
                    $add_data['trade_type'] = $goodsmodel->gettrade_type_by_name($add_data['trade_type']);
                }
                $add_data['PO_name'] = $poname;
                $add_data['mdate'] = time();
                $add_data['stat'] = 0;
                $add_data['uid'] = $this->USER['uid'];
                $checkadd = $opModel->where(array("PO_name" => $add_data['PO_name'], 'sku' => $add_data['sku']))->find();
                if (!$checkadd) {
					//var_dump($add_data);
					//die();
                    $opModel->add($add_data);
                }
            }

            $this->success("导入成功".$allRow);
        } else {
            $this->display();
        }
    }

    //上传后一步返回用户字段匹配
    function ajaxupload() {

        header("Content-type:text/html;charset=utf-8");
        if ($_FILES["files"]["error"] > 0) {
            exit('<script>parent.title = "Error：' . $_FILES["file"]["error"] . '";parent.code = "error";parent.tips_msg()</script>');
        }
        if (!$_FILES['files']['name']) {
            exit('<script>parent.title = "请选择需要导入的商品execl文件！";parent.code = "error";parent.tips_msg()</script>');
        }

        $ext = pathinfo($_FILES['files']['name'], PATHINFO_EXTENSION);
        if (!in_array($ext, array('xls', 'xlsx'))) {
            exit('<script>parent.title = "上传文件格式错误，必须是execl！";parent.code = "error";parent.tips_msg()</script>');
        }
        $upload_path = SITE_FILE . '/Uploads/';
        if (!file_exists($upload_path))
            mkdir($upload_path);
        $file_name = time() . rand(1000, 9999) . '.' . $ext;
        $filePath = $upload_path . $file_name;
        if (!move_uploaded_file($_FILES['files']['tmp_name'], $filePath)) {
            exit('<script>parent.title = "文件上传失败，请重新上传！";parent.code = "error";parent.tips_msg()</script>');
        }

        //读取字段
//        $OPModel = M("product_po");
//        $data = $OPModel->query("SHOW COLUMNS FROM `zt_product_po`");
//        $databasefilds = array();
////        file_put_contents("./test.txt",print_r($data,true));
//        foreach ($data as $key => $value) {
//            $databasefilds[] = $value['field'];
//        }

        $databasefilds[] = array('sku', "SKU货号");
        $databasefilds[] = array("ean13", 'ean13码');
        $databasefilds[] = array("name", '商品名');
        $databasefilds[] = array('ref_price', '参考价');
        $databasefilds[] = array('foreign_price', '境外价格');
        $databasefilds[] = array('local_price', '本币价格');
        $databasefilds[] = array('price', '网站建议零售价格');
        $databasefilds[] = array('lst_price', '列表价格');
        $databasefilds[] = array('cost_price', '成本价格');
        $databasefilds[] = array('market_price', '市场价格');
        $databasefilds[] = array('pom', '计量单位');
        $databasefilds[] = array('weight', '重量');
        $databasefilds[] = array('stock', '库存');
        $databasefilds[] = array('exp_time', '过期时间');
        $databasefilds[] = array('made_in', '原产国');
        $databasefilds[] = array('tax_no', '税号');
        $databasefilds[] = array('tax_xf', '消费税');
        $databasefilds[] = array('tax_gw', '关税');
        $databasefilds[] = array('tax_add', '增值税');
        $databasefilds[] = array('extra_info', '特别说明');
        $databasefilds[] = array('goods_brand_id', '商品品牌');
        $databasefilds[] = array('goods_type_id', '商品分类ID');
        $databasefilds[] = array('info_keywords', '关键字、');
        $databasefilds[] = array('trade_type', '贸易模式');

        $returndata = array(
            "databasefilds" => $databasefilds,
            "filepath" => base64_encode($filePath),
        );

        // 获取第一条的标题 给用户
        $PHPExcel = getExcelObj($filePath, $msg);
        if (!$PHPExcel) {
            exit('<script>parent.title = "上传的execl无数据，或者已损坏！";parent.code = "error";parent.tips_msg()</script>');
        }
        //加载数据
        //默认第一张表的数据
        $currentSheet = $PHPExcel->getSheet(0);
        //取得一共有多少列  
        $allColumn = $currentSheet->getHighestColumn();
        //取得一共有多少行  
        $allRow = $currentSheet->getHighestRow();

        //判断数据的条数
        if ($allRow <= 1) {
            exit('<script>parent.title = "上传的execl无数据，或者已损坏！";parent.code = "error";parent.tips_msg()</script>');
        }
        $excelfield = 'A,B,C,D,E,F,G,H,I,J,K,L,M,N,O,P,Q,R,S,T,U,V,W,X,Y,Z';
        $excelfield = explode(',', $excelfield);
        $excelTitle = array();
        $currentRow = 1;

        for ($currentColumn = 1; $excelfield[$currentColumn - 1] <= $allColumn; $currentColumn++) {
            //设置的字段获取数据组装
            $excelTitle[$currentColumn][1] = $PHPExcel->getActiveSheet()->getCell($excelfield[$currentColumn - 1] . $currentRow)->getValue();
            $excelTitle[$currentColumn][0] = $excelfield[$currentColumn - 1];
        }

        $returndata['excelfield'] = $excelTitle;

        $returndatastr = json_encode($returndata);
        exit('<script>parent.title = "上传成功";parent.tips_msg();parent.uplaodback(' . $returndatastr . ')</script>');
    }

}
